package fr.Castorflex.SpamYourFriend;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener, OnTouchListener {
	public final static String SENT = "SMS_SENT";
	private ProgressDialog pd;
	private final static int MENU_ABOUT = 1;
	public final static int MESSAGE_OK = 1256;
	public final static int MESSAGE_FAIL = 2754;
	private AutoCompleteTextView actvContact;
	private EditText etNbPosts;
	private EditText etMessage;
	private Button btnSend;
	private ArrayAdapter<String> adapter;
	Thread background;
	private int nbMessagesTotal;
	private int nbMessagesEnvoyes;
	private SeekBar progBar;
	private TextView tvRatioMessages;

	private Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MESSAGE_OK:
				nbMessagesEnvoyes++;
				tvRatioMessages.setText(nbMessagesEnvoyes + " / "
						+ nbMessagesTotal);
				if (progBar != null) {
					progBar.setProgress(nbMessagesEnvoyes);
				}
				
				/*
				 * if (pd != null) { pd.setProgress(nbMessages);
				 * Log.i(getClass().getName(), "" + System.currentTimeMillis());
				 * if (pd.getProgress() == pd.getMax()) pd.cancel(); }
				 */
				break;
			case MESSAGE_FAIL:
//				if (progBar != null)
//					progBar.setMax(nbMessagesEnvoyes);

			}
		}
	};

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// Handle your
			// messages
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		actvContact = ((AutoCompleteTextView) findViewById(R.id.AutoCompleteTextViewContact));
		etNbPosts = ((EditText) findViewById(R.id.editTextNbPosts));
		etMessage = ((EditText) findViewById(R.id.editTextMessage));
		btnSend = ((Button) findViewById(R.id.buttonSend));
		tvRatioMessages = ((TextView) findViewById(R.id.textViewNbMessagesEnvoyes));
		progBar = ((SeekBar) findViewById(R.id.ProgressBar));
		progBar.setClickable(false);
		progBar.setEnabled(false);

		btnSend.setOnClickListener(this);
		etMessage.setOnTouchListener(this);
		etNbPosts.setOnTouchListener(this);
		actvContact.setOnTouchListener(this);

		nbMessagesEnvoyes = 0;
		nbMessagesTotal = 0;

		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				Message msg = progressHandler.obtainMessage();
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					msg.what = Main.MESSAGE_OK;
					progressHandler.sendMessage(msg);
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					msg.what = Main.MESSAGE_FAIL;

					progressHandler.sendMessage(msg);
					Toast.makeText(getBaseContext(), "Error : Generic failure",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					msg.what = Main.MESSAGE_FAIL;
					progressHandler.sendMessage(msg);
					Toast.makeText(getBaseContext(), "No service",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					msg.what = Main.MESSAGE_FAIL;
					progressHandler.sendMessage(msg);
					Toast.makeText(getBaseContext(), "Null PDU",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					msg.what = Main.MESSAGE_FAIL;
					progressHandler.sendMessage(msg);
					Toast.makeText(getBaseContext(), "Radio off",
							Toast.LENGTH_SHORT).show();
					break;
				default:
					msg.what = Main.MESSAGE_FAIL;
					progressHandler.sendMessage(msg);
					Toast.makeText(getBaseContext(), "Unknown error",
							Toast.LENGTH_SHORT).show();

				}
			}
		}, new IntentFilter(SENT));

	}

	@Override
	protected void onResume() {
		// Somewhere in your code
		Message message = mHandler.obtainMessage(0);
		message.sendToTarget();

		// Another somewhere in your code
		mHandler.post(new Runnable() {
			public void run() {
				recupContacts();
			}
		});

		super.onResume();
	}

	private void recupContacts() {
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line);

		// get contacts
		Uri contactUri = ContactsContract.Contacts.CONTENT_URI;

		String[] PROJECTION = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.Contacts.HAS_PHONE_NUMBER, };

		String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";

		Cursor contacts = managedQuery(contactUri, PROJECTION, SELECTION, null,
				null);

		String name, number;
		Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String[] PHONES_PROJECTION = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
		String PHONE_SELECTION = null;

		contacts.moveToFirst();
		int total = contacts.getCount();
		if (total == 0)
			return;
		do {

			String contactId = contacts.getString(contacts
					.getColumnIndex(ContactsContract.Contacts._ID));

			PHONE_SELECTION = ContactsContract.CommonDataKinds.Phone.CONTACT_ID
					+ "=" + contactId;

			Cursor phones = managedQuery(phoneUri, PHONES_PROJECTION,
					PHONE_SELECTION, null,
					ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY
							+ " DESC");
			phones.moveToFirst();
			if (phones != null) {

				do {
					try {

						number = phones
								.getString(phones
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

						name = contacts
								.getString(contacts
										.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.append(name);
						stringBuilder.append(" - ");
						stringBuilder.append(number);
						adapter.add(stringBuilder.toString());
					} catch (Exception e) {
						Log.i(this.getClass().getName(), e.getMessage());
					}
				} while (phones.moveToNext());
				phones.close();
			}
		} while (contacts.moveToNext());
		contacts.close();

		actvContact.setAdapter(adapter);
	}

	private String recupNumeros() {
		String chaine = actvContact.getText().toString();

		chaine = chaine.replaceAll("[^[0-9+]]", "");

		// if (chaine.length() < 10 || chaine.length() > 11)
		// {
		// return null;
		// }
		// if (chaine.length() == 11)
		// chaine = "+" + chaine;
		return chaine;
	}

	@Override
	public void onClick(View v) {
		if (v == btnSend) {
			if (actvContact.getText().toString().length() > 0
					&& etNbPosts.getText().toString().length() > 0
					&& etMessage.getText().toString().length() > 0) {
				String[] contacts = { recupNumeros() };
				if (contacts != null && contacts.length > 0
						&& contacts[0].toString().length() > 0) {
					if (Integer.parseInt(etNbPosts.getText().toString()) <= 50
							&& Integer.parseInt(etNbPosts.getText().toString()) > 0) {
						afficherEnvoyerMessageConfirmDialog(
								this,
								"Do you really want to send "
										+ etNbPosts.getText().toString()
										+ " sms to " + contacts[0] + " ? ",
								contacts,
								etMessage.getText().toString(),
								Integer.parseInt(etNbPosts.getText().toString()));
					} else {
						MyDialog.afficherAlertDialog(this,
								"Please, select a number of posts <= 50 and > 0");
					}
				} else
					MyDialog.afficherAlertDialog(this, "Phone number not valid");
			} else
				MyDialog.afficherAlertDialog(this,
						"Please fill in all the fields");
		}

	}

	public void afficherEnvoyerMessageConfirmDialog(Context c, String str,
			final String[] contacts, final String message, final int nbMess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(c);
		builder.setMessage(str)
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								envoyerMessage(contacts, message, nbMess);
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void envoyerMessage(String[] contact, String message, int nbPosts) {
		/*
		 * pd = new ProgressDialog(this); pd.setCancelable(true);
		 * pd.setMessage("Sending sms ...");
		 * pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		 * pd.setProgress(0); pd.setMax(nbPosts);
		 */

		// pd.show();
		nbMessagesTotal += nbPosts;
		progBar.setMax(nbMessagesTotal);
		tvRatioMessages.setText(nbMessagesEnvoyes + " / " + nbMessagesTotal);

		SmsManager mgr = SmsManager.getDefault();

		PendingIntent sentIntent = PendingIntent.getBroadcast(
				getApplicationContext(), 0, new Intent(Main.SENT), 0);

//		int i = 0;
//		while(i < nbPosts){
//			mgr.sendTextMessage(contact[0], null, message, sentIntent, null);
//			++i;
//		}
		// create a thread for updating the progress bar
		background = new Thread(new MyThread(contact, message, nbPosts,
				progressHandler, this));

		background.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_ABOUT, Menu.NONE, "Informations");

		return true;
	}

	@Override
	protected void onPause() {
		adapter = null;
		super.onPause();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ABOUT:
			StringBuilder sb = new StringBuilder(
					"This application "
							+ "allows you to send 50 or less sms "
							+ "to your selected friend : \n"
							+ "Select a contact and the number of sms you want to send, "
							+ "then fill in the message in the field Message.\n"
							+ "Click on Send ! and let this app do the work !\n"
							+ "However, be carefull when you send a lot of sms, "
							+ "especially if you do not have illimited sms =)");
			MyDialog.afficherAlertDialog(this, sb.toString());
			return true;
		default:
			return false;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent arg1) {
		if (v == actvContact)
			actvContact.selectAll();
		else if (v == etMessage)
			etMessage.selectAll();
		else if (v == etNbPosts)
			etNbPosts.selectAll();
		return false;
	}
}